// pages/fans/fans.js
const { getFansList } = require("../../api/user.js");

Page({
  data: {
    // 粉丝列表
    fansList: [],
    // 分页参数
    pageIndex: 1,
    pageSize: 10,
    total: 0,
    hasMore: true,
    // 加载状态
    loading: false,
    refreshing: false,
  },

  onLoad() {
    // 页面加载时获取粉丝列表
    this.loadFansList();
  },

  // 加载粉丝列表
  async loadFansList(isRefresh = false) {
    try {
      if (isRefresh) {
        this.setData({ refreshing: true });
      } else {
        this.setData({ loading: true });
      }

      const params = {
        pageIndex: this.data.pageIndex,
        pageSize: this.data.pageSize,
      };

      console.log("获取粉丝列表参数:", params);

      const res = await getFansList(params);

      if (res && res.code === 0 && res.data) {
        const { list, total, hasNextPage } = res.data;

        let newFansList = [];
        if (isRefresh) {
          // 下拉刷新，替换列表
          newFansList = list || [];
        } else {
          // 上拉加载，追加到列表
          newFansList = [...this.data.fansList, ...(list || [])];
        }

        this.setData({
          fansList: newFansList,
          total: parseInt(total) || 0,
          hasMore: hasNextPage || false,
        });

        console.log("粉丝列表加载成功:", {
          currentPage: this.data.pageIndex,
          total: this.data.total,
          hasMore: this.data.hasMore,
          listLength: newFansList.length,
        });
      } else {
        console.error("获取粉丝列表失败:", res);
        wx.showToast({
          title: res.message || "获取粉丝列表失败",
          icon: "none",
        });
      }
    } catch (error) {
      console.error("加载粉丝列表失败:", error);
      wx.showToast({
        title: "网络错误，请重试",
        icon: "none",
      });
    } finally {
      this.setData({
        loading: false,
        refreshing: false,
      });
    }
  },

  // 上拉加载更多
  onReachBottom() {
    if (this.data.hasMore && !this.data.loading) {
      this.setData({
        pageIndex: this.data.pageIndex + 1,
      });
      this.loadFansList();
    }
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.setData({
      pageIndex: 1,
      fansList: [],
      hasMore: true,
    });
    this.loadFansList(true).finally(() => {
      wx.stopPullDownRefresh();
    });
  },

  // 格式化性别
  formatGender(gender) {
    switch (gender) {
      case 1:
        return "男";
      case 2:
        return "女";
      default:
        return "未知";
    }
  },

  // 格式化头像URL
  formatAvatarUrl(avatarUrl) {
    if (!avatarUrl || avatarUrl.trim() === "") {
      return "/images/default-avatar.png";
    }
    return avatarUrl;
  },

  // 格式化昵称
  formatNickname(nickname) {
    if (!nickname || nickname.trim() === "") {
      return "微信用户";
    }
    return nickname;
  },
});
